package com.gambi.tapestry.components;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.RenderSupport;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.ClientBehaviorSupport;
import org.apache.tapestry5.services.Request;
import org.slf4j.Logger;

//@GWT(entryPoint=GWTUI.class, entryPointName="com.gambi.example.gwtUI")
public abstract class GWTComponent{

	@Inject
	private Logger logger;

	// NOTE the different injections used here
	@Environmental
	private RenderSupport pageRenderSupport;

	@Inject
	private RenderSupport renderSupport;
	
	
	@Environmental
	private ClientBehaviorSupport clientBehaviorSupport;

	@Inject
	private ComponentResources componentResources;

	@Inject
	private Request request;

	
	private String assignedClientId;
	
	@Parameter(defaultPrefix = BindingConstants.LITERAL)
	private String zone;

	@Parameter(defaultPrefix = BindingConstants.LITERAL)
	private String event;

	public String getType() {
		return this.getClass().getCanonicalName().replace(".", "-");
	}

	@SetupRender
	void setup(){
		System.out.println("GWTComponent.setup()");
		assignedClientId = renderSupport.allocateClientId( componentResources.getId() );
	}
	
	public String getClientID() {
		return assignedClientId;
	}

	public String getCompleteID() {
		// Alessio

		// return request.getContextPath() + request.getPath() + ":" +
		// componentResources.getId();
		String path = request.getContextPath() + "/"
				+ componentResources.getCompleteId();// .replaceFirst(":", "?");
		logger.info("completeid {} {}", componentResources.getCompleteId(),
				path);
		// return componentResources.getCompleteId().replaceFirst(":", "?");
		return path;
	}

	public String getZone() {
		if (zone == null)
			return "";
		return "zone: \"" + zone + "\",";
	}

	// Here also the GWTUI entry point library should be added ...
	@Log
	void beginRender(MarkupWriter writer) {
		if (zone != null) {
			clientBehaviorSupport.addZone(zone, null, null);
		}
	}
}
